using System;
using System.Threading;
using System.Windows.Forms;
using RFS.BizLogic.Sys.impl;
using RFS.BizLogic.utils;

namespace ProtoWinform
{
    public static class GlobalExceptionHandler
    {
        private static ILog _log;
        public static void Initialize()
        {
            _log = AntiObject.Ins.Get<ILog>();
            
            Application.ThreadException += Application_ThreadException;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            HandleException(e.Exception);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            HandleException(e.ExceptionObject as Exception);
        }

        private static void HandleException(Exception ex)
        {
            // Log the exception details 
            string errorMessage = $"An unhandled exception occurred: {ex.Message}\n{ex.StackTrace}";
            // Log to file, database, or any other desired location
            // ...

            // Display a user-friendly error message
            // MessageBox.Show(
            //     "An unexpected error occurred. Please try again or contact support for assistance.",
            //     "Error",
            //     MessageBoxButtons.OK,
            //     MessageBoxIcon.Error);
            _log?.Err(ex);

            // Optionally, terminate the application
            // Application.Exit(); 
        }
    }
}